package com.example.studymybatis.service.impl;

import com.example.studymybatis.constant.UserConstant;
import com.example.studymybatis.dao.UserMapper;
import com.example.studymybatis.model.User;
import com.example.studymybatis.model.UserExample;
import com.example.studymybatis.model.dto.UserLoginRequest;
import com.example.studymybatis.model.vo.UserVO;
import com.example.studymybatis.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * 用户层实现类
 */

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserVO loginUser(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 1. 校验参数
        if(userLoginRequest == null) {
            return null;
        }
        String username = userLoginRequest.getUsername();
        String password = userLoginRequest.getPassword();

        if (StringUtils.isAnyBlank(username, password)) {
            return null;
        }
        // 2. 查询数据库验证用户是否合法
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        }
        User user = users.get(0);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        // 3. 将用户信息保存到session中
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, userVO);
        return userVO;
    }
}
